import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'login.dart';
import 'constants.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      // theme: ThemeData(
      //   primarySwatch: Colors.green,
      // ),
      home: const RegistrationPage(),
    );
  }
}

class RegistrationPage extends StatelessWidget {
  const RegistrationPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.white,
        centerTitle: true,
        title: const Text(
          '注册',
          style: TextStyle(fontSize: 20, color: Colors.black),
        ),
        leading: IconButton(
          icon: const Icon(
            Icons.arrow_back,
            color: Colors.black54,
          ),
          onPressed: () {
            Navigator.pop(context); // 更改为 pop，从而不会重复添加页面
          },
        ),
      ),
      body: const RegistrationForm(),
    );
  }
}

class RegistrationForm extends StatefulWidget {
  const RegistrationForm({Key? key}) : super(key: key);

  @override
  _RegistrationFormState createState() => _RegistrationFormState();
}

class _RegistrationFormState extends State<RegistrationForm> {
  final TextEditingController _phoneController = TextEditingController();
  final TextEditingController _passwordController = TextEditingController();
  final TextEditingController _smsController = TextEditingController();
  final String serverUrl = AppConstants.serverUrl;
  bool _obscureText = true;
  late HighlightButtons roleChoice;

  @override
  void initState() {
    super.initState();
    roleChoice = HighlightButtons();
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          roleChoice,
          const SizedBox(height: 20.0),
          _buildTextField(_phoneController, '请输入手机号'),
          const SizedBox(height: 10.0),
          _buildPasswordTextField(_passwordController, '请设置密码'),
          const SizedBox(height: 10.0),
          _buildTextField(_smsController, '请输入验证码'),
          const SizedBox(height: 20.0),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: <Widget>[
              _buildElevatedButton('注册', _registerUser),
              _buildElevatedButton('获取验证码', _getSMS),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildTextField(TextEditingController controller, String hintText) {
    return Container(
      width: 250.0,
      padding: EdgeInsets.symmetric(horizontal: 20.0),
      decoration: BoxDecoration(
        border: Border.all(color: Color.fromARGB(255, 179, 202, 193)),
        borderRadius: BorderRadius.circular(10.0),
        color: Colors.white,
      ),
      child: TextField(
        controller: controller,
        decoration: InputDecoration(
          hintText: hintText,
          border: InputBorder.none,
        ),
      ),
    );
  }

  Widget _buildPasswordTextField(
      TextEditingController controller, String hintText) {
    return Container(
      width: 250.0,
      padding: EdgeInsets.symmetric(horizontal: 20.0),
      decoration: BoxDecoration(
        border: Border.all(color: Color.fromARGB(255, 179, 202, 193)),
        borderRadius: BorderRadius.circular(10.0),
        color: Colors.white,
      ),
      child: TextField(
        controller: controller,
        decoration: InputDecoration(
          hintText: hintText,
          border: InputBorder.none,
          suffixIcon: GestureDetector(
            onTap: () {
              setState(() {
                _obscureText = !_obscureText;
              });
            },
            child: Icon(
              _obscureText ? Icons.visibility : Icons.visibility_off,
            ),
          ),
        ),
        obscureText: _obscureText,
      ),
    );
  }

  Widget _buildElevatedButton(String label, Function() onPressed) {
    return ElevatedButton(
      onPressed: onPressed,
      child: Text(label),
      style: ButtonStyle(
        backgroundColor: MaterialStateProperty.all<Color>(
            Color.fromARGB(255, 179, 202, 193)), // Set the background color
        minimumSize: MaterialStateProperty.all<Size>(
            Size(10, 40)), // Set the minimum size
      ),
    );
  }

  void _registerUser() async {
    final phone = _phoneController.text;
    final password = _passwordController.text;
    final sms = _smsController.text;

    if (phone.isEmpty || password.isEmpty || sms.isEmpty) {
      _showErrorDialog('错误', '请填写所有字段');
      return;
    }

    final requestData = {
      'phone': phone,
      'password': password,
      'sms': sms,
      "role": roleChoice.getRole(),
    };
    final header = {'Content-Type': 'application/json'};

    try {
      final Uri uri =
          Uri.parse('$serverUrl/v1/register'); // Adjust the path accordingly
      print(uri);
      final response = await http.post(
        uri,
        headers: header,
        body: jsonEncode(requestData), // Convert data to JSON string
      );
      print('request data: $requestData');
      final responseBody = response.body;
      print('Registration response: $responseBody');
      if (response.statusCode == 200) {
        _showSuccessDialog('注册成功', '您已成功注册。');
      } else if (response.statusCode == 400) {
        // 解析JSON字符串
        final Map<String, dynamic> responseData = json.decode(responseBody);
        // 从Map中获取errorcode的值
        final int errorCode = responseData['errorcode'];
        if (errorCode == 40002) {
          _showErrorDialog('注册失败', '无效的手机号');
        } else if (errorCode == 40004) {
          _showErrorDialog('注册失败', '验证码错误，请重新输入。');
        } else if (errorCode == 40003) {
          _showErrorDialog('注册失败', '密码长度应为6-16位。');
        } else if (errorCode == 40008) {
          _showErrorDialog('注册失败', '无效的身份。');
        } else if (errorCode == 40005) {
          _showErrorDialog('注册失败', '用户已存在。');
        } else if (errorCode == 40001) {
          _showErrorDialog('注册失败', '无效的json格式。');
        }
      } else if (response.statusCode == 500) {
        _showErrorDialog('注册失败', '服务器异常请稍后重试。');
      }
    } catch (e) {
      _showErrorDialog('错误', '发生了一个未知错误，请稍后重试。');
      print(e);
    }
  }

  void _showErrorDialog(String title, String content) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return _buildAlertDialog(title, content);
      },
    );
  }

  void _showSuccessDialog(String title, String content) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return _buildAlertDialog(title, content);
      },
    );
  }

  AlertDialog _buildAlertDialog(String title, String content) {
    return AlertDialog(
      title: Text(title),
      content: Text(content),
      actions: [
        TextButton(
          child: const Text('确定'),
          onPressed: () {
            Navigator.of(context).pop(); // 确保这里使用的是对话框的上下文
          },
        ),
      ],
    );
  }

  void _getSMS() async {
    final phone = _phoneController.text;

    if (phone.isEmpty) {
      _showErrorDialog('错误', '请输入手机号');
      return;
    }

    final requestData = {
      'phone': phone,
    };

    try {
      final Uri uri = Uri.parse('$serverUrl/v1/getSMSCode?phone=$phone');
      final response = await http.get(uri);
      final responseBody = response.body;
      print('Registration response: $responseBody');
      if (response.statusCode == 200) {
        showDialog(
          context: context,
          builder: (BuildContext context) {
            return AlertDialog(
              title: const Text('获取验证码成功'),
              content: const Text('验证码已发送，请注意查收。'),
              actions: [
                TextButton(
                  child: const Text('确定'),
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                ),
              ],
            );
          },
        );
      } else if (response.statusCode == 400) {
        final Map<String, dynamic> responseData = json.decode(responseBody);
        final int errorCode = responseData['errorcode'];
        if (errorCode == 40002) {
          _showErrorDialog('获取验证码失败', '无效的手机号');
        } else if (errorCode == 40005) {
          _showErrorDialog('获取验证码失败', '用户已存在');
        }
      } else if (response.statusCode == 500) {
        _showErrorDialog('获取验证码失败', '服务器异常请稍后重试。');
      }
    } catch (e) {
      _showErrorDialog('错误', '发生了一个错误，请稍后重试。');
    }
  }

  @override
  void dispose() {
    _phoneController.dispose();
    _passwordController.dispose();
    _smsController.dispose();
    super.dispose();
  }
}
